package com.jshoperxms.components.wechat;

import com.jshoperxms.Response;
import com.jshoperxms.components.redis.RedisUtils;
import com.jshoperxms.controller.api.langdu.MemberController;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.SHA1;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.MemberEnums;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.entity.MemberT;
import com.jshoperxms.service.MemberTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sdywcd on 2018/9/26.
 * Des:微信授权操作基础类方法
 */
@RestController
@RequestMapping("/wx")
public class WxBaseController extends BaseTController {


    @Resource
    private MemberTService memberTService;


    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private MemberController memberController;



    @RequestMapping(value="/getWxMSessionKey",method= RequestMethod.GET)
    public ResponseEntity getWxMSessionKey(String code){
        String redumkey=PrimaryKey.get().toString();
        Map<String,Object> responsedata=new HashMap<>();
        String url="https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        Map<String,Object>params=new HashMap<>();
        params.put("appid",WxConfig.appid);
        params.put("secret",WxConfig.serect);
        params.put("code",code);
        ResponseEntity<WxSessionKeyBean>tkb=restTemplate.getForEntity(url,WxSessionKeyBean.class,params);
        if (tkb.getStatusCode().equals(HttpStatus.OK)){
            WxSessionKeyBean sessionKeyBean=tkb.getBody();
            if(sessionKeyBean.getOpenid()!=null&&sessionKeyBean.getSession_key()!=null){
                redisUtils.setObjectEx(redumkey,2592000,sessionKeyBean.getOpenid()+sessionKeyBean.getSession_key());
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put("membersession",redumkey);
                responsedata.put("openid",sessionKeyBean.getOpenid());
                //调用保存用户数据方法
                saveOrUpdateWxMemberinfo(responsedata,sessionKeyBean);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }


    private void saveOrUpdateWxMemberinfo(Map resp,WxSessionKeyBean rq) {
        //1先检查会员是否存在
        if (StringUtils.isNotBlank(rq.getOpenid())) {
            MemberT bean = checkDuplicatesByOpenid(rq.getOpenid());
            if (bean == null) {
                //如果openid不存在说明用户第一次进入
                bean = new MemberT();
                bean.setId(PrimaryKey.get().toString());
                bean.setTotalbelove(0);
                bean.setBirthday(StaticKey.EMPTY);
                bean.setBlood(StaticKey.EMPTY);
                bean.setCity(StaticKey.EMPTY);
                bean.setConstellation(StaticKey.EMPTY);
                bean.setCreatetime(DateTools.getSystemTimeLong());
                bean.setCreatorid(BaseTools.getAdminCreateId());
                bean.setDes(StaticKey.EMPTY);
                bean.setDistrict(StaticKey.EMPTY);
                bean.setEmail(StaticKey.EMPTY);
                bean.setHeadpath("http://tong12.nos-eastchina1.126.net/defaulthead.png");
                bean.setIntegration(BigDecimal.valueOf(0.0));//累计积分
                bean.setLoginname(StaticKey.EMPTY);
                bean.setLoginpwd(SHA1.getDigestOfString("qweasd"));
                bean.setTotalloveother(0);
                bean.setMemberGroupId(StaticKey.EMPTY);
                bean.setMemberGroupName(StaticKey.EMPTY);
                bean.setMemberstate(MemberEnums.MemberState.ACTIVE.getState());
                bean.setMerrystatus(MemberEnums.MemberMerryStatus.UNDEFINED.getState());
                bean.setMid(SHA1.getDigestOfString(bean.getId()));//加密的会员id
                bean.setMobile(StaticKey.EMPTY);
                bean.setNick(StaticKey.EMPTY);
                bean.setPostingcount(0);
                bean.setProvince(StaticKey.EMPTY);
                bean.setQq(StaticKey.EMPTY);
                bean.setRealname(StaticKey.EMPTY);
                bean.setSex(StaticKey.EMPTY);
                bean.setSinaweibo(StaticKey.EMPTY);
                bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                bean.setTag(StaticKey.EMPTY);
                bean.setTelno(StaticKey.EMPTY);
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(1);
                bean.setWeixin(StaticKey.EMPTY);
                bean.setWhichsex(StaticKey.EMPTY);
                bean.setWxopenid(rq.getOpenid());
                bean.setWxsessionkey(rq.getSession_key());
                memberTService.save(bean);
                //初始化会员等级信息
                memberController.initMemberGrade(bean);
                //初始化阅读状态
                memberController.initYdStatus(bean);
                //初始化小树状态
                memberController.initSmallTree(bean);
            } else {
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(bean.getVersiont() + 1);
                bean.setWxsessionkey(rq.getSession_key());
                memberTService.update(bean);
            }
            resp.put("memberid",bean.getId());
        }

    }


    public MemberT checkDuplicatesByOpenid(String str) {
        Criterion criterion = Restrictions.eq("wxopenid", str);
        MemberT bean = this.memberTService.findOneByCriteria(MemberT.class, criterion);
        if (bean != null) {
            return bean;
        }
        return null;
    }

}
